package com.youku.component.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public abstract class SqlConnector implements Connector {

	private Connection connection;

	protected Map<String, String> map;

	@Override
	public Connector build(Map<String, String> map) {
		this.map = map;
		try {
			Class.forName(driver());
		} catch (ClassNotFoundException e) {
			throw new IllegalArgumentException("数据库驱动信息填写错误", e);
		}

		try {
			connection = DriverManager.getConnection(url(), map.get("user"), map.get("password"));
			return this;
		} catch (SQLException e) {
			throw new IllegalArgumentException("数据库连接信息填写错误", e);
		}
	}

	protected abstract String driver();

	protected abstract String url();

	protected int port() {
		String port = map.get("port");
		return port == null ? defaultPort() : Integer.parseInt(port);
	}

	protected String ip() {
		String ip = map.get("ip");
		ip = StringUtils.isBlank(ip) ? "localhost" : ip;
		return ip;
	}

	public Connection getConnection() {
		return connection;
	}

}
